﻿using SmartSapce.ServiceLocation;
using SmartSpace.Core;
using SmartSpace.Packaging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SmartSpace.WebApp._console.wizzard
{
    public partial class deploy_application_template : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();
            List<SiteTemplate> themes = service.GetSiteTemplates();
            if (themes != null && themes.Count > 0)
            {
                Response.Redirect("./create-application.aspx");
            }
        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            if (_ctlFileTemplate.HasFile)
            {
                string outDir = Server.MapPath("~/_temp/") + Guid.NewGuid().ToString("D");
                Stream stream = new MemoryStream(_ctlFileTemplate.FileBytes);
                PackageUtil.DecompressFile(stream, outDir);

                DirectoryInfo di = new DirectoryInfo(outDir);
                string file = di.GetFiles("*.xtml")[0].FullName;
                
                XTemplate xTemplate = PackageUtil.ParseXTML(file);

                // 移动文件
                foreach (XFile xFile in xTemplate.Files)
                {
                    string destFile = Server.MapPath("~\\") + xFile.Publish;
                    string sourceFile = Path.Combine(outDir, xFile.Path);

                    FileInfo fi = new FileInfo(destFile);
                    if (!fi.Directory.Exists)
                    {
                        Directory.CreateDirectory(fi.Directory.FullName);
                    }

                    if (File.Exists(destFile))
                    {
                        File.Delete(destFile);
                    }
                    File.Move(sourceFile, destFile);
                }

                Directory.Delete(outDir, true);

                ICoreService coreService = ServiceLocator.Get<ICoreService>();
                SiteTemplate theme = new SiteTemplate();
                theme.Id = xTemplate.Id;
                theme.Caption = xTemplate.Caption;
                theme.Name = xTemplate.Name;
                theme.Package = xTemplate.Package;
                theme.PreviewImageUrl = xTemplate.PreviewImageUrl;
                theme.Type = xTemplate.Type;
                theme.Version = xTemplate.Version;
                if (coreService.SaveSiteTemplate(theme))
                {
                    Response.Redirect("./create-application.aspx");
                }
            }
            else
            {
                Response.Redirect("./deploy-application-template.aspx");
            }
        }
    }
}